import pygame
import random
import sys

# 初始化Pygame
pygame.init()

# 游戏配置常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PURPLE = (128, 0, 128)
BALLOON_COLORS = [RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE]  # 气球颜色列表

# 设置屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("打气球游戏 🎈")

# 时钟（控制帧率）
clock = pygame.time.Clock()

# 字体设置
font_small = pygame.font.Font(None, 36)
font_large = pygame.font.Font(None, 72)

# 气球类
class Balloon:
    def __init__(self):
        self.radius = random.randint(20, 40)  # 随机半径（大小）
        self.color = random.choice(BALLOON_COLORS)  # 随机颜色
        # 随机位置（确保气球完全在屏幕内）
        self.x = random.randint(self.radius, SCREEN_WIDTH - self.radius)
        self.y = SCREEN_HEIGHT + self.radius  # 从屏幕底部生成
        self.speed = random.randint(1, 3)  # 上升速度（随机）
        self.is_popped = False  # 是否被爆破

    def draw(self):
        """绘制气球（主体+绳子）"""
        if not self.is_popped:
            # 绘制气球主体（圆形）
            pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
            # 绘制气球绳子（直线）
            pygame.draw.line(screen, BLACK, (self.x, self.y + self.radius), 
                           (self.x, self.y + self.radius + 20), 2)

    def move(self):
        """气球上升移动"""
        if not self.is_popped:
            self.y -= self.speed

    def check_click(self, mouse_x, mouse_y):
        """检查是否被鼠标点击（计算距离）"""
        if not self.is_popped:
            distance = ((mouse_x - self.x)**2 + (mouse_y - self.y)**2)**0.5
            return distance <= self.radius  # 点击范围在气球半径内
        return False

    def is_off_screen(self):
        """检查气球是否超出屏幕顶部"""
        return self.y + self.radius < 0

# 游戏初始化函数
def init_game():
    global balloons, score, time_left, spawn_rate, last_spawn_time
    balloons = []  # 气球列表
    score = 0  # 分数
    time_left = 60  # 游戏时间（秒）
    spawn_rate = 1000  # 气球生成间隔（毫秒，初始1秒1个）
    last_spawn_time = pygame.time.get_ticks()  # 上次生成气球的时间

# 显示文本函数
def draw_text(text, font, color, x, y, center=False):
    text_surface = font.render(text, True, color)
    if center:
        text_rect = text_surface.get_rect(center=(x, y))
    else:
        text_rect = text_surface.get_rect(topleft=(x, y))
    screen.blit(text_surface, text_rect)

# 游戏主循环
def game_loop():
    init_game()
    running = True
    game_over = False

    while running:
        # 控制帧率
        clock.tick(FPS)

        # 事件处理
        for event in pygame.event.get():
            # 退出游戏
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            # 鼠标点击（爆破气球）
            if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
                if event.button == 1:  # 左键点击
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    # 遍历所有气球，检查是否点击
                    for balloon in balloons[:]:  # 切片避免遍历中修改列表
                        if balloon.check_click(mouse_x, mouse_y):
                            balloon.is_popped = True
                            score += 10  # 每爆破一个加10分
                            # 移除被爆破的气球（避免占用内存）
                            balloons.remove(balloon)

        # 游戏未结束时的逻辑
        if not game_over:
            # 计时逻辑
            current_time = pygame.time.get_ticks()
            time_left = 60 - (current_time // 1000 - start_time // 1000)
            if time_left <= 0:
                game_over = True

            # 生成气球（根据间隔时间）
            if current_time - last_spawn_time > spawn_rate:
                balloons.append(Balloon())
                last_spawn_time = current_time
                # 难度递增：每得100分，生成间隔减少100毫秒（最低300毫秒）
                if score % 100 == 0 and spawn_rate > 300:
                    spawn_rate -= 100

            # 气球移动和移除（超出屏幕或被爆破）
            for balloon in balloons[:]:
                balloon.move()
                if balloon.is_off_screen() or balloon.is_popped:
                    balloons.remove(balloon)

        # 绘制背景（白色）
        screen.fill(WHITE)

        # 绘制气球
        for balloon in balloons:
            balloon.draw()

        # 绘制游戏信息（分数、时间）
        draw_text(f"分数: {score}", font_small, BLACK, 20, 20)
        draw_text(f"时间: {max(time_left, 0)}秒", font_small, BLACK, SCREEN_WIDTH - 200, 20)

        # 游戏结束界面
        if game_over:
            draw_text("游戏结束!", font_large, RED, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 50, center=True)
            draw_text(f"最终分数: {score}", font_small, BLACK, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 20, center=True)
            draw_text("点击关闭窗口退出", font_small, BLACK, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 60, center=True)

        # 更新屏幕显示
        pygame.display.flip()

# 记录游戏开始时间
start_time = pygame.time.get_ticks()

# 启动游戏
if __name__ == "__main__":
    print("游戏说明：")
    print("1. 鼠标左键点击气球进行爆破")
    print("2. 每爆破一个气球得10分")
    print("3. 时间结束前，分数越高越好")
    print("4. 分数越高，气球生成速度越快（难度递增）")
    game_loop()